package com.atguigu.bookcity.controller;


import com.atguigu.bookcity.entity.ShoppingCart;
import com.atguigu.bookcity.entity.User;
import com.atguigu.bookcity.entity.vo.orderVo;
import com.atguigu.bookcity.service.ShoppingCartService;
import com.atguigu.bookcity.vo.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hxx
 * @since 2021-03-19
 */
@CrossOrigin
@RestController
//登录才可以访问此接口
@Api(value = "登录访问购物车", tags = {"购物车"})
@RequestMapping("/bookcity/shopping-cart")
public class ShoppingCartController {


    @Resource
    private ShoppingCartService cartService;

    //添加购物车
    @PostMapping("/addCart")
    public CommonResult addCart(@RequestBody orderVo orderVo) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        int num = cartService.addCart(userId, orderVo);
        if (num > 0) {
            return CommonResult.ok();
        }
        return CommonResult.error();
    }

    //修改数量
    @PostMapping("/updateNumber")
    public CommonResult updateNum(@RequestBody orderVo orderVo) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        //购物车中的商品数量修改，根据条件update书的数量
        cartService.updateNumber(userId, orderVo);
        return CommonResult.ok();
    }

    @GetMapping("/getAllcart")
    public CommonResult getAllCart() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        List<ShoppingCart> shoppingCarts = cartService.getAllCart(userId);
        return CommonResult.ok().data(userId, shoppingCarts);
    }


    @ApiOperation(
            value = "批量删除购物车",
            notes = "登录访问",
            produces = "application/json")
    @PostMapping("/deletecarts")
    public CommonResult deleteCartByBatch(@RequestParam List<String> bookIds) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        cartService.removeCartsByIds(bookIds, user.getId());
        return CommonResult.ok();
    }
}



